package lysjmaster.base.file.upload.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.ZipUtil;
import lombok.extern.slf4j.Slf4j;
import lysjmaster.base.common.spring.base.BaseController;
import lysjmaster.base.common.spring.base.BaseService;
import lysjmaster.base.common.spring.pagination.PageRequestDTO;
import lysjmaster.base.common.spring.pagination.PageVo;
import lysjmaster.base.common.web.ParamUtil;
import lysjmaster.base.common.web.Resp;
import lysjmaster.base.common.web.RespUtil;
import lysjmaster.base.file.upload.domain.UploadInfo;
import lysjmaster.base.file.upload.service.UploadFileService;
import lysjmaster.base.file.upload.service.UploadInfoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ZhangWenJian
 * @data 2019/1/4--17:12
 * @description
 */
@Slf4j
@RestController
@RequestMapping("/fms/upload")
public class UploadInfoController extends BaseController<UploadInfo, PageRequestDTO> {
    @Resource
    private UploadInfoService uploadInfoService;

    @Resource
    private UploadFileService uploadFileService;

    @Override
    public BaseService<UploadInfo> getService() {
        return uploadInfoService;
    }


    @Value("${file.upload.path}")
    public String prefixPath;

    @Value("${file.upload.certPath}")
    private String certPath; // 微信支付证书路径

    @Value("${file.upload.wordPath}")
    private String wordPath; // word文档路径

    @Value("${file.upload.htmlPath}")
    private String htmlPath; // html文档路径

    @Value("${file.upload.zipPath}")
    private String zipPath; // zip文档路径


    @PostMapping("/files_upload/{project}/{module}")
    public Resp filesUpload(MultipartFile[] files, String uploaderId, @PathVariable String project, @PathVariable String module) {
        System.err.println(files.length);
        if ("undefined".equals(project) || ParamUtil.isBlank(project)) {
            return RespUtil.error(Resp.ResStatus.PARAM_ERROR, "请填写来源项目!");
        }
        if ("undefined".equals(module) || ParamUtil.isBlank(module)) {
            return RespUtil.error(Resp.ResStatus.PARAM_ERROR, "请填写来源模块!");
        }
        return uploadFileService.filesUpload(files, uploaderId, project, module);
    }

    /**
     * @author Created by wtl on 2019/5/8 22:10
     * @Description 上传文件，返回文件路径
     */
    @PostMapping("/file_upload")
    public Resp fileUpload(MultipartFile file, String module) {
        log.info("上传文件文件夹：{}", module);
        if (module == null) {
            return RespUtil.error(Resp.ResStatus.PARAM_ERROR, "请指定模块名!");
        }
        if (file == null || file.isEmpty()) {
            return RespUtil.error(Resp.ResStatus.PARAM_ERROR, "文件为空!");
        }
        String fileName = "";
        String path = "";
        // 微信授权文件txt存放目录
        if (module.startsWith("static")) {
            fileName = file.getOriginalFilename();
            path = "C:/" + module;
        } else {
            fileName = ParamUtil.uuid() + ".p12";
            path = certPath + module;
        }
        File dest = new File(path, fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        // 如果是压缩文件则解压,并删除zip
        if ("zip".equalsIgnoreCase(FileUtil.extName(dest.getAbsolutePath()))) {
            ZipUtil.unzip(dest.getAbsolutePath(), dest.getParent(), Charset.forName("gbk"));
            dest.delete();
        }
        return RespUtil.success(dest.getAbsolutePath(), "上传成功");
    }

    /*
     * @author drj
     * @date 2019-08-05 18:49
     * @Description :上传word文档
     */
    @PostMapping("/word_upload")
    public Resp wordUpload(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return RespUtil.error(Resp.ResStatus.PARAM_ERROR, "文件为空!");
        }
        //获取上传文件后缀名
        String OriginalfileName = file.getOriginalFilename();// 获取文件名
        String suffixName = OriginalfileName.substring(OriginalfileName.lastIndexOf(".")); // 获取文件的后缀名
        log.info("文件后缀名：" + suffixName);
        //校验后缀名是否符合规范
        boolean flag = ReUtil.isMatch(".(doc|DOC|docx|DOCX)$", suffixName);
        if (!flag) {
            return RespUtil.error(Resp.ResStatus.PARAM_ERROR, "文件仅支持doc、DOC、docx、DOCX格式");
        }
        String fileName = ParamUtil.uuid() + ".docx";
        File dest = new File(wordPath, fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        return RespUtil.success(dest.getAbsolutePath(), "上传成功");
    }


    @PostMapping("/path/file_upload")
    public Resp pathFileUpload(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return RespUtil.error(Resp.ResStatus.PARAM_ERROR, "文件为空!");
        }
        //获取上传文件后缀名
        String OriginalfileName = file.getOriginalFilename();// 获取文件名
        String suffixName = OriginalfileName.substring(OriginalfileName.lastIndexOf(".")); // 获取文件的后缀名
        log.info("文件后缀名：" + suffixName);
        //校验后缀名是否符合规范
        boolean flag = ReUtil.isMatch(".(jpg|png|jpeg|JPG|PNG|JPEG)$", suffixName);
        if (!flag) {
            return RespUtil.error(Resp.ResStatus.PARAM_ERROR, "图片仅支持jpg、png、jpeg、JPG、PNG、JPEG格式");
        }
        //创建文件
        String fileName = ParamUtil.uuid() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        File dest = new File(prefixPath, fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        Map<String, String> map = new HashMap<>();
        map.put("fileName", fileName);
        map.put("path", dest.getAbsolutePath());
        return RespUtil.success(map, "上传成功");
    }


//    @GetMapping("/list_rewrite")
//    public Resp listRewrite(UploadInfo entity, PageVo pageVo) {
//        return uploadInfoService.listRewrite(entity, pageVo);
//    }

    @GetMapping("/resource/{fileId}")
    public void showFiles(HttpServletRequest request, HttpServletResponse response, @PathVariable String fileId) throws IOException {
        if ("undefined".equals(fileId) || ParamUtil.isBlank(fileId)) {
            return;
        }
        uploadFileService.showFiles(request, response, false, fileId);
    }


    @GetMapping("/resource/path/{fileId}")
    public String showFilePath(@PathVariable String fileId) throws IOException {
        if ("undefined".equals(fileId) || ParamUtil.isBlank(fileId)) {
            return "";
        }
        return uploadFileService.showFilePath(false, fileId);
    }


    @GetMapping("/resource/thumbnail/{fileId}")
    public void showThumbnailFiles(HttpServletRequest request, HttpServletResponse response, @PathVariable String fileId) throws IOException {
        if ("undefined".equals(fileId) || ParamUtil.isBlank(fileId)) {
            return;
        }
        uploadFileService.showFiles(request, response, true, fileId);
    }


    @PostMapping("/common_upload")
    public Resp htmlUpload(MultipartFile file, String suffix, String serviceProviderId) {
        if (ParamUtil.isBlank(serviceProviderId)) {
            return RespUtil.error(Resp.ResStatus.INNER_ERROR, "获取{1}id失败");
        }
        if (file == null || file.isEmpty()) {
            return RespUtil.error(Resp.ResStatus.PARAM_ERROR, "文件为空!");
        }
        //获取上传文件后缀名
        String originalFileName = file.getOriginalFilename();// 获取文件名
        String suffixName = originalFileName.substring(originalFileName.lastIndexOf(".")); // 获取文件的后缀名
        log.info("文件后缀名：" + suffixName);
        //文件路径
        String path = "";
        //校验后缀名是否符合规范
        if (suffix.equals("html") || suffix.equals("HTML")) {
            boolean flag = ReUtil.isMatch(".(html|HTML)$", suffixName);
            if (!flag) {
                return RespUtil.error(Resp.ResStatus.PARAM_ERROR, "上传文件只支持html、HTML格式");
            }
            path = htmlPath + "/" + serviceProviderId;
        } else if (suffix.equals("zip") || suffix.equals("ZIP")) {
            boolean flag = ReUtil.isMatch(".(zip|ZIP)$", suffixName);
            if (!flag) {
                return RespUtil.error(Resp.ResStatus.PARAM_ERROR, "上传文件只支持zip、ZIP格式");
            }
            path = zipPath + "/" + serviceProviderId;
        }
        //创建文件
        File dest = new File(path, originalFileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        Map<String, String> map = new HashMap<>();
        map.put("fileName", originalFileName);
        return RespUtil.success(map, "上传成功");
    }


}
